from urllib import parse

from django import template
from django.urls import reverse

from ceph.ceph_settings import get_yunkun_config

register = template.Library()


@register.simple_tag
def get_yunkun_signin_name_url(request):
    hostname = f'{request.scheme}://{request.get_host()}'
    local_endpoint, yunkun_auth_endpoint, yunkun_auth_name, jwt_public_key = get_yunkun_config()

    yunkun_auth_endpoint = yunkun_auth_endpoint.rstrip('/')

    if local_endpoint and yunkun_auth_endpoint and jwt_public_key:

        callllback_url = reverse('auth-callback-yunkun')
        if hostname not in hostname:
            return None

        callback_url = f'{hostname}{callllback_url}'
        query = parse.urlencode(query={'clientUrl': f'{callback_url}'})
        url = f'{yunkun_auth_endpoint}/open/api/AAILogin/askUrlRedirect?{query}'

        if not yunkun_auth_name:
            yunkun_auth_name = '中国科技云身份认证联盟(CSTCLOUD AAI)'

        return {'name': yunkun_auth_name, 'url': url}

    return None
